import axios, { AxiosRequestConfig } from 'axios';

interface Response<T> {
  message: string;
  code: number;
  data: T;
}

export default class HttpRequest {
  request: <T>(options: AxiosRequestConfig) => Promise<T>;
  constructor(baseURL: string) {
    // userStore使用
    const service = axios.create({
      baseURL: baseURL,
      timeout: 5000
    });
    service.interceptors.request.use(
      (config) => ({
        ...config
      }),
      (error) => Promise.reject(error)
    );

    service.interceptors.response.use(
      (response) => response,
      (error) => {
        return Promise.reject(error);
      }
    );
    const request = async <T>(options: AxiosRequestConfig): Promise<T> => {
      const {
        data: { data, message, code }
      } = await service.request<Response<T>>(options);
      if (code !== 200) {
        return Promise.reject(message);
      }
      return data;
    };

    this.request = request;
  }
}
